package com.hindua.ailaaicuaai;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hindua.utils.NetworkState;
import com.rtst.widget.actionbar.ActionBarActivity;
import com.hindua.ailaaicuaai.R;

public class NoNetworkActivity extends ActionBarActivity {

	private Handler mHandler;
	private ProgressBar mProgressBar;
	private Intent mIntent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new Handler();
		setContentView(R.layout.no_network_layout);
		mIntent = (Intent) getIntent().getExtras().get("INTENT");
		final Button btnRetry = (Button) findViewById(R.id.btn_reconnect);
		mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
		mProgressBar.setVisibility(View.GONE);
		final TextView label = (TextView) findViewById(R.id.label_no_network);
		
		btnRetry.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View view) {
				mProgressBar.setVisibility(View.VISIBLE);
				label.setVisibility(View.GONE);
				btnRetry.setVisibility(View.GONE);
				if ((new NetworkState(NoNetworkActivity.this)).hasConnection()) {
					finish();
					startActivity(mIntent);
				} else {
					mHandler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							mProgressBar.setVisibility(View.GONE);
							label.setVisibility(View.VISIBLE);
							btnRetry.setVisibility(View.VISIBLE);
						}
					}, 1000);
				}
			}
		});
	}

	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Bạn muốn đóng ứng dụng ?")
		.setCancelable(true)
		.setPositiveButton("Có", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
				onDestroy();
				MainActivity.getInstance().finish();
				System.runFinalizersOnExit(true);
				System.exit(0);
			}
		})
		.setNegativeButton("Không", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				onResume();
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.setCancelable(false);
		alertDialog.show();
	}
}
